using System;
using System.Collections.Generic;
using UnityEngine;

namespace Framework.Core
{
    public class CustomPool<T>
    {
        public int Count { get { return _list.Count; } }
        private Func<T> _createFunction;
        private readonly Queue<T> _list = new Queue<T>();
        public EditPoolInfo Info { get; private set; }
        public CustomPool(Func<T> create, int count = 0)
        {
            Info = new EditPoolInfo(typeof(T));
            _createFunction = create;
            if (count < 1) return;
            if (count > 1000)
            {
                count = 1000;
            }
            Info.Push(count);
            while (count-- > 0)
            {
                _list.Enqueue(_createFunction());
            }
        }
        public void Clear(int count, Action<T> itemCallback = null)
        {
            int len = Mathf.Min(_list.Count, count);
            while (len-- > 0)
            {
                var ins = _list.Dequeue();
                itemCallback?.Invoke(ins);
            }
        }
        public T Get()
        {
            Info.Pop();
            if (_list.Count > 0)
            {
                Info.Push(-1);
                return _list.Dequeue();
            }
            return _createFunction();
        }
        public void Release(T value)
        {
            if (value == null) return;
            //if (_list.Contains(value)) return;
            Info.Pop(-1);
            Info.Push(1);
            _list.Enqueue(value);
        }
    }
}
